using System;
using System.Collections.Generic;
using System.Linq;

namespace MT5Trade.Models
{
    /// <summary>
    /// 波动率聚类分析结果
    /// 用于存储和分析GARCH模型检测到的波动率聚类模式
    /// </summary>
    public class VolatilityCluster
    {
        #region 属性

        /// <summary>
        /// 高波动率时期列表
        /// </summary>
        public List<VolatilityPeriod> HighVolatilityPeriods { get; set; }

        /// <summary>
        /// 低波动率时期列表
        /// </summary>
        public List<VolatilityPeriod> LowVolatilityPeriods { get; set; }

        /// <summary>
        /// 中等波动率时期列表
        /// </summary>
        public List<VolatilityPeriod> MediumVolatilityPeriods { get; set; }

        /// <summary>
        /// 波动率转换点（regime change points）
        /// </summary>
        public List<int> RegimeChangePoints { get; set; }

        /// <summary>
        /// 聚类强度（0-1之间，越接近1表示聚类越明显）
        /// </summary>
        public double ClusteringStrength { get; set; }

        /// <summary>
        /// 当前波动率状态
        /// </summary>
        public VolatilityState CurrentState { get; set; }

        /// <summary>
        /// 波动率持续性度量（自相关系数）
        /// </summary>
        public double VolatilityPersistence { get; set; }

        /// <summary>
        /// 平均聚类持续时间（周期数）
        /// </summary>
        public double AverageClusterDuration { get; set; }

        /// <summary>
        /// 所有波动率时期（合并高、中、低波动率时期）
        /// </summary>
        public List<VolatilityPeriod> Periods
        {
            get
            {
                var allPeriods = new List<VolatilityPeriod>();
                allPeriods.AddRange(HighVolatilityPeriods);
                allPeriods.AddRange(MediumVolatilityPeriods);
                allPeriods.AddRange(LowVolatilityPeriods);
                return allPeriods.OrderBy(p => p.StartIndex).ToList();
            }
        }

        /// <summary>
        /// 交易建议（兼容性属性）
        /// </summary>
        public TradingRecommendation Recommendation => GetTradingRecommendation();

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化波动率聚类分析结果
        /// </summary>
        public VolatilityCluster()
        {
            HighVolatilityPeriods = new List<VolatilityPeriod>();
            LowVolatilityPeriods = new List<VolatilityPeriod>();
            MediumVolatilityPeriods = new List<VolatilityPeriod>();
            RegimeChangePoints = new List<int>();
            CurrentState = VolatilityState.Medium;
            ClusteringStrength = 0;
            VolatilityPersistence = 0;
            AverageClusterDuration = 0;
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 分析聚类特征
        /// </summary>
        /// <returns>分析摘要</returns>
        public string AnalyzeClusteringPatterns()
        {
            var summary = new System.Text.StringBuilder();
            
            summary.AppendLine("===== 波动率聚类分析 =====");
            summary.AppendLine($"聚类强度: {ClusteringStrength:P2}");
            summary.AppendLine($"波动率持续性: {VolatilityPersistence:F4}");
            summary.AppendLine($"平均聚类持续时间: {AverageClusterDuration:F1} 个周期");
            summary.AppendLine($"当前状态: {GetStateDescription(CurrentState)}");
            summary.AppendLine();
            
            summary.AppendLine($"高波动率时期: {HighVolatilityPeriods.Count} 个");
            if (HighVolatilityPeriods.Any())
            {
                var avgDuration = HighVolatilityPeriods.Average(p => p.Duration);
                var avgLevel = HighVolatilityPeriods.Average(p => p.AverageVolatility);
                summary.AppendLine($"  - 平均持续时间: {avgDuration:F1} 个周期");
                summary.AppendLine($"  - 平均波动率水平: {avgLevel:F6}");
            }
            
            summary.AppendLine($"低波动率时期: {LowVolatilityPeriods.Count} 个");
            if (LowVolatilityPeriods.Any())
            {
                var avgDuration = LowVolatilityPeriods.Average(p => p.Duration);
                var avgLevel = LowVolatilityPeriods.Average(p => p.AverageVolatility);
                summary.AppendLine($"  - 平均持续时间: {avgDuration:F1} 个周期");
                summary.AppendLine($"  - 平均波动率水平: {avgLevel:F6}");
            }
            
            summary.AppendLine($"状态转换点: {RegimeChangePoints.Count} 个");
            
            return summary.ToString();
        }

        /// <summary>
        /// 获取投资建议
        /// </summary>
        /// <returns>基于聚类分析的投资建议</returns>
        public TradingRecommendation GetTradingRecommendation()
        {
            var recommendation = new TradingRecommendation();

            // 基于当前波动率状态给出建议
            switch (CurrentState)
            {
                case VolatilityState.High:
                    recommendation.PositionSizing = PositionSizingAdvice.Reduce;
                    recommendation.RiskLevel = VolatilityRiskLevel.High;
                    recommendation.Strategy = "降低仓位，增加止损距离，避免频繁交易";
                    break;
                    
                case VolatilityState.Low:
                    recommendation.PositionSizing = PositionSizingAdvice.Increase;
                    recommendation.RiskLevel = VolatilityRiskLevel.Low;
                    recommendation.Strategy = "可适度增加仓位，紧缩止损，寻找突破机会";
                    break;
                    
                case VolatilityState.Medium:
                    recommendation.PositionSizing = PositionSizingAdvice.Normal;
                    recommendation.RiskLevel = VolatilityRiskLevel.Medium;
                    recommendation.Strategy = "维持常规仓位和风控策略";
                    break;
                    
                case VolatilityState.Transitioning:
                    recommendation.PositionSizing = PositionSizingAdvice.Reduce;
                    recommendation.RiskLevel = VolatilityRiskLevel.Medium;
                    recommendation.Strategy = "波动率处于转换期，建议观望或降低仓位";
                    break;
            }

            // 基于聚类强度调整建议
            if (ClusteringStrength > 0.7)
            {
                recommendation.Confidence = "高";
                recommendation.AdditionalNote = "波动率聚类特征明显，状态预测可靠性较高";
            }
            else if (ClusteringStrength > 0.4)
            {
                recommendation.Confidence = "中";
                recommendation.AdditionalNote = "存在一定的波动率聚类，需结合其他指标";
            }
            else
            {
                recommendation.Confidence = "低";
                recommendation.AdditionalNote = "波动率聚类不明显，建议谨慎使用该分析结果";
            }

            return recommendation;
        }

        /// <summary>
        /// 计算下一期最可能的波动率状态
        /// </summary>
        /// <param name="transitionMatrix">状态转移矩阵</param>
        /// <returns>预测的下一期状态</returns>
        public VolatilityState PredictNextState(double[,] transitionMatrix = null)
        {
            if (transitionMatrix == null)
            {
                // 使用默认的转移概率
                transitionMatrix = GetDefaultTransitionMatrix();
            }

            int currentStateIndex = (int)CurrentState;
            double maxProbability = 0;
            VolatilityState nextState = CurrentState;

            for (int i = 0; i < 4; i++)
            {
                if (transitionMatrix[currentStateIndex, i] > maxProbability)
                {
                    maxProbability = transitionMatrix[currentStateIndex, i];
                    nextState = (VolatilityState)i;
                }
            }

            return nextState;
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 获取状态描述
        /// </summary>
        private string GetStateDescription(VolatilityState state)
        {
            return state switch
            {
                VolatilityState.Low => "低波动率",
                VolatilityState.Medium => "中等波动率",
                VolatilityState.High => "高波动率",
                VolatilityState.Transitioning => "转换期",
                _ => "未知"
            };
        }

        /// <summary>
        /// 获取默认的状态转移矩阵
        /// 基于经验的波动率状态转移概率
        /// </summary>
        private double[,] GetDefaultTransitionMatrix()
        {
            // 行：当前状态，列：下一状态
            // 顺序：Low, Medium, High, Transitioning
            return new double[,]
            {
                { 0.7, 0.25, 0.03, 0.02 }, // Low -> 各状态
                { 0.15, 0.6, 0.15, 0.1 },  // Medium -> 各状态
                { 0.02, 0.18, 0.7, 0.1 },  // High -> 各状态
                { 0.2, 0.4, 0.2, 0.2 }     // Transitioning -> 各状态
            };
        }

        #endregion
    }

    /// <summary>
    /// 波动率时期
    /// </summary>
    public class VolatilityPeriod
    {
        /// <summary>开始索引</summary>
        public int StartIndex { get; set; }

        /// <summary>结束索引</summary>
        public int EndIndex { get; set; }

        /// <summary>持续时间（周期数）</summary>
        public int Duration => EndIndex - StartIndex + 1;

        /// <summary>平均波动率</summary>
        public double AverageVolatility { get; set; }

        /// <summary>最大波动率</summary>
        public double MaxVolatility { get; set; }

        /// <summary>最小波动率</summary>
        public double MinVolatility { get; set; }

        /// <summary>波动率标准差</summary>
        public double VolatilityStdDev { get; set; }

        /// <summary>风险级别</summary>
        public VolatilityRiskLevel RiskLevel { get; set; }
    }

    /// <summary>
    /// 波动率状态枚举
    /// </summary>
    public enum VolatilityState
    {
        /// <summary>低波动率</summary>
        Low = 0,
        
        /// <summary>中等波动率</summary>
        Medium = 1,
        
        /// <summary>高波动率</summary>
        High = 2,
        
        /// <summary>转换期（regime switching）</summary>
        Transitioning = 3
    }

    /// <summary>
    /// 交易建议
    /// </summary>
    public class TradingRecommendation
    {
        /// <summary>仓位调整建议</summary>
        public PositionSizingAdvice PositionSizing { get; set; }

        /// <summary>风险等级</summary>
        public VolatilityRiskLevel RiskLevel { get; set; }

        /// <summary>策略描述</summary>
        public string Strategy { get; set; }

        /// <summary>建议置信度</summary>
        public string Confidence { get; set; }

        /// <summary>附加说明</summary>
        public string AdditionalNote { get; set; }

        /// <summary>
        /// 仓位调整系数（兼容性属性）
        /// </summary>
        public double PositionSizeAdjustment
        {
            get
            {
                return PositionSizing switch
                {
                    PositionSizingAdvice.Reduce => 0.5,
                    PositionSizingAdvice.Normal => 1.0,
                    PositionSizingAdvice.Increase => 1.5,
                    _ => 1.0
                };
            }
        }

        /// <summary>
        /// 止损距离建议（基于风险等级的动态止损）
        /// 遵循风险管理原则：高风险需要更大的止损空间
        /// </summary>
        public double StopLossDistance
        {
            get
            {
                return RiskLevel switch
                {
                    VolatilityRiskLevel.Low => 0.02,    // 低风险：2%止损
                    VolatilityRiskLevel.Medium => 0.03, // 中等风险：3%止损
                    VolatilityRiskLevel.High => 0.05,   // 高风险：5%止损
                    _ => 0.03
                };
            }
        }

        /// <summary>
        /// 获取建议摘要
        /// </summary>
        public string GetSummary()
        {
            return $"仓位建议: {GetPositionSizingDescription()}\n" +
                   $"风险等级: {GetRiskLevelDescription()}\n" +
                   $"策略: {Strategy}\n" +
                   $"置信度: {Confidence}\n" +
                   $"说明: {AdditionalNote}";
        }

        private string GetPositionSizingDescription()
        {
            return PositionSizing switch
            {
                PositionSizingAdvice.Reduce => "减少仓位",
                PositionSizingAdvice.Normal => "维持常规仓位",
                PositionSizingAdvice.Increase => "可适度增加仓位",
                _ => "观望"
            };
        }

        private string GetRiskLevelDescription()
        {
            return RiskLevel switch
            {
                VolatilityRiskLevel.Low => "低风险",
                VolatilityRiskLevel.Medium => "中等风险",
                VolatilityRiskLevel.High => "高风险",
                _ => "未知"
            };
        }
    }

    /// <summary>
    /// 仓位调整建议枚举
    /// </summary>
    public enum PositionSizingAdvice
    {
        /// <summary>减少仓位</summary>
        Reduce,
        
        /// <summary>正常仓位</summary>
        Normal,
        
        /// <summary>增加仓位</summary>
        Increase
    }

    /// <summary>
    /// 波动率风险等级枚举
    /// </summary>
    public enum VolatilityRiskLevel
    {
        /// <summary>低风险</summary>
        Low,
        
        /// <summary>中等风险</summary>
        Medium,
        
        /// <summary>高风险</summary>
        High
    }
}